﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbouiCOM;

namespace BoAddonBiz_FreightForwarder.Approval
{
    class B1Form_ApprovalTemplates : SAPBoAddon.B1Form
    {
        #region override
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
            switch (frmEditMode)
            {
                case SAPBoAddon.frmItemEditMode.fe_AddMode:
                    this.Matrix_AutoAddLine();
                    InitOrderType();
                    CurrentForm.Items.Item("19").Specific.Selected = true;
                    CurrentForm.Items.Item("mtx_4").Visible = false;
                    break;
            }
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            this.FormSetting.FormType = B1FormTypes.ado_AVA_FF_ApprovalTemplates;
            this.FormSetting.FormFileName = "AVA_ApprovalTemForm.srf";

            FormSetting.AutoGetObjectNextNumber = false;
            #region Matrix Setting
            FormSetting.MatrixSetting.MtxUID = "mtx_1";
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.MenuAddNewLine = true;
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_1";
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = false;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "LineId";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_WTM1";
            FormSetting.MatrixSetting.Add();

            FormSetting.MatrixSetting.MtxUID = "mtx_2";
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.MenuAddNewLine = true;
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_1";
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = false;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "LineId";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_WTM3";
            FormSetting.MatrixSetting.Add();

            FormSetting.MatrixSetting.MtxUID = "mtx_3";
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.MenuAddNewLine = true;
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_1";
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = false;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "LineId";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_WTM2";
            FormSetting.MatrixSetting.Add();

            FormSetting.MatrixSetting.MtxUID = "mtx_4";
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.MenuAddNewLine = true;
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_1";
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = false;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "LineId";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_WTM4";
            FormSetting.MatrixSetting.Add();

            #endregion
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            //用户
            Utils.InitialMatrixComboBox(SBOCompany, this.CurrentForm.Items.Item("mtx_1").Specific, "col_1", "UserID", "U_Name", "OUSR");
            //部门
            Utils.InitialMatrixComboBox(SBOCompany, this.CurrentForm.Items.Item("mtx_1").Specific, "col_2", "Code", "Name", "OUDP", null, "", null, true);
        }
        #endregion
        #region construction
        public B1Form_ApprovalTemplates()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_ApprovalTemplates_frm_ItemEvent);
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_ApprovalTemplates_frm_ChooseFormListEvent);
        }
        #endregion
        #region Events

        void B1Form_ApprovalTemplates_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            SAPbouiCOM.DBDataSource dbds = default(SAPbouiCOM.DBDataSource);
            if (pVal.Before_Action)
            {
            }
            else
            {
                if (pVal.Action_Success)
                {
                    //审批级别
                    if (pVal.ChooseFromListUID == "CFL_1")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_WTM2");
                        SAPbouiCOM.Matrix mtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item(pVal.ItemUID).Specific;
                        dbds.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(mtx, pVal.Row, "col_f", dbds);
                        mtx.GetLineData(pVal.Row);
                        dbds.SetValue("U_WstCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_AppCode", 0).ToString());
                        dbds.SetValue("U_WstName", dbds.Offset, pVal.SelectedObjects.GetValue("U_AppName", 0).ToString());
                        mtx.SetLineData(pVal.Row);

                    }                   
                }
            }

        }
        void B1Form_ApprovalTemplates_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    SaveBeforeCheck(pVal.FormUID, ref BubbleEvent);
                }
            }
            else
            {
                #region Panel
                if (pVal.ItemUID == "tab_1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 1;
                }
                if (pVal.ItemUID == "tab_2" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 2;
                }
                if (pVal.ItemUID == "tab_3" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 3;
                }
                if (pVal.ItemUID == "tab_4" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 4;
                }
                #endregion
                if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_1" && pVal.ItemChanged)
                {
                    GetDepartment(pVal.Row);
                }
                if (pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    if (pVal.ItemUID == "19")
                    {
                        CurrentForm.Items.Item("19").Specific.Selected = true;
                        CurrentForm.Items.Item("mtx_4").Visible = false;
                    }
                    if (pVal.ItemUID == "20")
                    {
                        CurrentForm.Items.Item("20").Specific.Selected = true;
                        CurrentForm.Items.Item("mtx_4").Visible = true;
                    }
                }
                if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_1" && (pVal.ItemChanged || pVal.EventType == BoEventTypes.et_COMBO_SELECT))
                {
                    SAPBoAddon.B1Assistant.Matrix.AutoAddNewLine(this.CurrentForm, "mtx_1", "col_f", "@AVA_WTM1", -1, "Lineid", "Lineid", true);
                }
            }
        }
        #endregion
        #region Methods
        /// <summary>
        /// 保存之前检查Code、Name
        /// </summary>
        /// <param name="FormUID"></param>
        /// <param name="BubbleEvent"></param>
        private void SaveBeforeCheck(string FormUID, ref bool BubbleEvent)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            SAPbobsCOM.Recordset ors;
            SAPbouiCOM.Matrix oMtx;
            string ApprovalCode = string.Empty;

            oForm = SBOApp.Forms.Item(FormUID);
            #region 检查审批模板编码和名称是否为空
            dbds = oForm.DataSources.DBDataSources.Item("@AVA_OWTM");
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            if (oForm.Mode != BoFormMode.fm_ADD_MODE && oForm.Mode != BoFormMode.fm_UPDATE_MODE && oForm.Mode != BoFormMode.fm_EDIT_MODE) return;

            ApprovalCode = dbds.GetValue("U_AppCode", dbds.Offset).Trim();
            if (string.IsNullOrEmpty(ApprovalCode))
            {
                BubbleEvent = false;
                SBOApp.MessageBox("名称不能为空，请检查！");
                return;
            }
            if (oForm.Mode == BoFormMode.fm_ADD_MODE)
            {
                ors.DoQuery("SELECT COUNT(1) FROM [@AVA_OWTM] Where U_AppCode='" + ApprovalCode + "'");
                if (ors.Fields.Item(0).Value > 0)
                {
                    BubbleEvent = false;
                    SBOApp.MessageBox("此名称：" + ApprovalCode + " 已存在系统中，请检查！");
                    return;
                }
            }

            ors.DoQuery("SELECT Autokey FROM ONNM  Where ObjectCode = 'AVA_ApprovalTem'");
            dbds.SetValue("Code", dbds.Offset, ors.Fields.Item("Autokey").Value);
            dbds.SetValue("Name", dbds.Offset, ors.Fields.Item("Autokey").Value);
            #endregion
            #region 审批单据的选择
            oMtx = oForm.Items.Item("mtx_2").Specific;
            for (int i = 1; i <= oMtx.VisualRowCount; i++)
            {
                dynamic Item = oMtx.GetCellSpecific("col_1", i);
                if (Item.Checked != true)
                {
                    oMtx.DeleteRow(i);
                    i--;
                }
            }
            if (oMtx.VisualRowCount <= 0)
            {
                SBOApp.MessageBox("请选择需要审批的单据！");
                oForm.PaneLevel = 2;
                InitOrderType();
                BubbleEvent = false;
            }
            #endregion
        }
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="row"></param>
        private void GetDepartment(int row)
        {
            SAPbouiCOM.Matrix oMtx = CurrentForm.Items.Item("mtx_1").Specific;
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SAPbouiCOM.ComboBox oComboBox = oMtx.GetCellSpecific("col_1", row);
            ors.DoQuery("SELECT Department FROM OUSR Where UserID = " + oComboBox.Selected.Value);
            if (ors.RecordCount > 0)
            {
                oComboBox = oMtx.GetCellSpecific("col_2", row);
                string DeptCode = ors.Fields.Item("Department").Value.ToString();
                oComboBox.SelectExclusive(DeptCode, BoSearchKey.psk_ByValue);
            }
        }
        /// <summary>
        /// 初始化订单类型
        /// </summary>
        private void InitOrderType()
        {
            #region 加载单据类型
            SAPbouiCOM.Matrix oMtx;
            SAPbobsCOM.Recordset ors;
            SAPbouiCOM.DBDataSource dbds;

            dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_WTM3");
            oMtx = CurrentForm.Items.Item("mtx_2").Specific;
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            dbds.Clear();
            ors.DoQuery(@"SELECT ISNULL(T1.DocEntry,ROW_NUMBER() over( order by t1.docentry desc)) DocEntry,
	                        Case When ISNULL(U_ObjectCode,'') = '' then T0.Code else U_ObjectCode End U_ObjectCode,
	                        Case When ISNULL(U_ObjectName,'') = '' then T0.Name else U_ObjectName End U_ObjectName,U_IsAutokey,U_Length
                        FROM OUDO T0
	                        FULL JOIN [@AVA_FF_ONNM] T1 ON t0.Code = T1.U_ObjectCode
                        Where T0.[TYPE] = '3'
                             And Not T0.Code IN (
                                'AVA_FF_OrderNumber',
                                'AVA_FF_Inventory',
                                'AVA_FF_GoodsReceipt',
                                'AVA_FF_GoodsIssue',
                                'AVA_FF_AirLine',
                                'AVA_FF_AirLine',
                                'AVA_FF_AffixUpload',
                                'AVA_Control',
                                'AVA_AU_TARGET',
                                'AVA_ApprovalTem',
                                'AVA_ApprovalStep',
                                'AVA_ApprovalStages')");
            for (int i = 0; i < ors.RecordCount; i++)
            {
                dbds.InsertRecord(i);
                dbds.SetValue("U_TransType", i, ors.Fields.Item("U_ObjectCode").Value);
                dbds.SetValue("U_TransName", i, ors.Fields.Item("U_ObjectName").Value);
                ors.MoveNext();
            }
            oMtx.LoadFromDataSourceEx();
            oMtx.AutoResizeColumns();
            #endregion
        }
        #endregion
    }
}
